import { NextResponse, NextRequest } from 'next/server';
import { getUserIdFromAuthHeader } from '@/lib/auth';
import { updateWish, deleteWish } from '@/lib/wishes';

// 适配 Next.js 16 的类型：context.params 为 Promise
export async function PATCH(request: NextRequest, context: { params: Promise<{ id: string }> }) {
  try {
    const userId = getUserIdFromAuthHeader(request);
    if (!userId) {
      return NextResponse.json({ error: '未授权' }, { status: 401 });
    }
    const { id } = await context.params;
    const numericId = Number(id);
    if (Number.isNaN(numericId)) {
      return NextResponse.json({ error: 'ID无效' }, { status: 400 });
    }
    const body = await request.json();
    const updated = await updateWish(userId, numericId, {
      content: body.content,
      type: body.type,
      convertToAchieved: body.convert === true,
    });
    if (!updated) {
      return NextResponse.json({ error: '未找到或无权限' }, { status: 404 });
    }
    return NextResponse.json({ message: '更新成功', record: updated });
  } catch (error) {
    console.error('更新愿望错误:', error);
    return NextResponse.json({ error: '服务器错误' }, { status: 500 });
  }
}

export async function DELETE(request: NextRequest, context: { params: Promise<{ id: string }> }) {
  try {
    const userId = getUserIdFromAuthHeader(request);
    if (!userId) {
      return NextResponse.json({ error: '未授权' }, { status: 401 });
    }
    const { id } = await context.params;
    const numericId = Number(id);
    if (Number.isNaN(numericId)) {
      return NextResponse.json({ error: 'ID无效' }, { status: 400 });
    }
    const ok = await deleteWish(userId, numericId);
    if (!ok) {
      return NextResponse.json({ error: '未找到或无权限' }, { status: 404 });
    }
    return NextResponse.json({ message: '删除成功' });
  } catch (error) {
    console.error('删除愿望错误:', error);
    return NextResponse.json({ error: '服务器错误' }, { status: 500 });
  }
}